""" DescGenerator for 'desc' generator in AutoTagSearcher """

from S3D.AutoTagSearcher import Callback
from S3D.DescCompiler import DescCompiler as Compiler
from S3D.MultiGenerator.Generators.MacrosGenerator import MacrosGenerator
from S3D.Decorators import singleton

@singleton
class DescGenerator(Callback):
    def register(self, searcher):
        searcher.addGenerator("desc", self)

    def begin(self, info):
        self.map = {}

    def end(self, info):
        self.map = None

    def input(self, params, text, info):
        if len(params) != 1:
            info.addError("'desc': single parameter with name expected")
            return

        name = params[0]
        if name in self.map.keys():
            info.addError("'%s': redifinition" % name)
            info.addErrorInfo("see previous declaraion", self.map[name].file, self.map[name].line)
            return

        c = Compiler()
        ctxt = c.compile(text, info.file, info.line)

        if ctxt == None:
            info.errorMsg += c.errorMsg
            info.errorsCount += c.errorsCount
            return

        ctxt.file = info.file
        ctxt.line = info.line
        
        self.map[name] = ctxt

    def output(self, params, info):
        if len(params) < 2:
            info.addError("'desc': desc and macros names were expected")
            return

        name = params[0]
        if name not in self.map.keys():
            info.addError("'%s': unknown desc definition" % name)
            return

        ctxt = self.map[name]

        locals = dict(
            descs   = ctxt.descs,
            structs = ctxt.structs,
            types   = ctxt.types,
            ctxt    = ctxt
        )

        return MacrosGenerator().outputEx(params[1:], info, locals)
